import HTMLParser
import re

class htmlstring(object):
   def __init__(self, String):
      self._regex = re.compile("((%[0-9a-fA-F]{1,2}){1,2})")
      self._string = None

      if String:
         self._string = String

   @property
   def original(self):
      return self._string

   def __str__(self):
      match = self._regex.findall(self._string)
      retval = None
      for ix in match:
         temp = int(ix.replace("%", "0x"), 16)
         try:
            retval = self._string.replace(ix, unichr(temp).encode('utf-8'))
         except UnicodeDecodeError, message:
            print message, temp

      if not retval:
         retval = self._string

      return retval

   def __repr__(self):
      return repr(str(self))

   def __unicode__(self):
      return unicode(str(self))

class PyLinkParser(HTMLParser.HTMLParser):
   def __init__(self):
      HTMLParser.HTMLParser.__init__(self)
      self._links = []

   def __len__(self):
      return len(self._links)

   @property
   def links(self):
      return self._links

   def handle_starttag(self, tag, attrs):
      if tag == 'a':
         (href, link) = attrs[0]
         print attrs
         repkg = re.compile("^/pypi/(.*)/(.*)")
         match = repkg.search(link)
         if match:
            package = str(htmlstring(match.groups()[0]))
            version = str(htmlstring(match.groups()[1]))
            self._links.append((package, version))
